package cn.enilu.flash.service.transport;

import cn.enilu.flash.bean.dto.transport.MapLineDto;
import cn.enilu.flash.bean.dto.transport.MapPointDto;
import cn.enilu.flash.bean.dto.transport.TranspOrderSubmitDto;
import cn.enilu.flash.bean.entity.transport.MapLine;
import cn.enilu.flash.bean.entity.transport.MapPoint;
import cn.enilu.flash.bean.entity.transport.TransportOrder;
import cn.enilu.flash.bean.exception.ApplicationException;
import cn.enilu.flash.bean.exception.ApplicationExceptionEnum;
import cn.enilu.flash.bean.exception.ServiceExceptionEnum;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.bean.vo.transport.TransportOrderDetailVo;
import cn.enilu.flash.bean.vo.transport.UserAddressVo;
import cn.enilu.flash.dao.transport.MapLineRepository;
import cn.enilu.flash.dao.transport.MapPointRepository;
import cn.enilu.flash.dao.transport.TransportOrderRepository;
import cn.enilu.flash.security.JwtUtil;
import cn.enilu.flash.service.BaseService;
import cn.enilu.flash.utils.HttpUtil;
import cn.enilu.flash.utils.Lists;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class TransportOrderService extends BaseService<TransportOrder,Long, TransportOrderRepository> {

    @Autowired
    private TransportOrderRepository transportOrderRepository;
    @Autowired
    private MapPointRepository mapPointRepository;
    @Autowired
    private MapService mapService;

    @Autowired
    private MapLineRepository mapLineRepository;

    private Snowflake snowflake;

    @PostConstruct
    public void init(){

        Long workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr()) >> 16 & 31;
        Long dataCenterId = 1L;
        snowflake = IdUtil.getSnowflake(workerId, dataCenterId);
    }


    public TransportOrderDetailVo getOrderDetail(Long orderId){
        TransportOrder userOrder = transportOrderRepository.getOne(orderId);

        SearchFilter filter = SearchFilter.build("groupId", SearchFilter.Operator.EQ, userOrder.getMapLineId());
        List<MapLine> mapLineList = mapService.queryAll(filter);



        if(CollectionUtils.isEmpty(mapLineList)){
            throw new ApplicationException(ApplicationExceptionEnum.DATA_ERROR);
        }
        MapLine mapLine = mapLineList.get(0);


        List<MapPoint> pointList = mapPointRepository.findList(mapLine.getGroupId());
        List<MapLine> pLineList = mapLineRepository.findAll();


        for(MapLine line : pLineList){
            log.info("line>>{}", line);
            List<MapPoint> list = line.getPointList();
            log.info("line.getPointList()>>{}",list);
        }


        TransportOrderDetailVo vo = new TransportOrderDetailVo();
        /*
        SearchFilter filter = SearchFilter.build("createBy", SearchFilter.Operator.EQ, findDto.getUserId());
        SearchFilter filter1 = SearchFilter.build("point.pointType", SearchFilter.Operator.EQ, 3);
        List<UserAddress> list = queryAll(Lists.newArrayList(filter,filter1), Sort.by(Sort.Direction.ASC, "orderBy"));
        * */
        vo.setMapLine(mapLine);

        return vo;

    }


    /**
     * 提交货运订单
     * @param submitDto
     * @return
     */
    public TransportOrder submitOrder(TranspOrderSubmitDto submitDto){

        List<MapPointDto> pointDtoList = submitDto.getMapPoints();


        validateAndInit(submitDto);


        Long roadId = snowflake.nextId();

        MapLine mapLine = new MapLine();
        mapLine.setGroupId(roadId);
        mapLine.setCreateTime(new Date());
        mapLine.setCreateBy(submitDto.getUserId());

        List<MapPoint> mapPointList = Lists.newArrayList();
        for(MapPointDto point : pointDtoList){
            MapPoint mapPoint = new MapPoint();
            mapPoint.setLongitude(point.getLongitude());
            mapPoint.setLatitude(point.getLatitude());
            mapPoint.setCity(point.getCity());
            mapPoint.setProvince(point.getProvince());
            mapPoint.setDistrict(point.getDist());
            mapPoint.setAddressDetails(point.getAddDetail());
            mapPoint.setCreateTime(new Date());
            mapPoint.setCreateBy(submitDto.getUserId());

            mapPointList.add(mapPoint);
        }


        TransportOrder transportOrder = new TransportOrder();
        transportOrder.setMapLineId(roadId);
        transportOrder.setSubmitTime(new Date());
        transportOrder.setServerTime(submitDto.getServerTime());
        transportOrder.setLoadingType(submitDto.getLoadingType());
        transportOrder.setCarType(submitDto.getCarType());
        transportOrder.setPrice(submitDto.getPrice());
        transportOrder.setCreateTime(submitDto.getSubmitTime());
        transportOrder.setCreateBy(submitDto.getUserId());

        TransportOrder ddw = null;
        try {
            mapLine = mapLineRepository.save(mapLine);

            for(MapPoint point : mapPointList){
                point.setRoadId(roadId);
            }
            mapPointRepository.saveAll(mapPointList);

            transportOrder = transportOrderRepository.save(transportOrder);
        } catch (Exception e) {
            log.error("e>>",e);
            MapPoint delPoint = new MapPoint();
            delPoint.setRoadId(roadId);
            mapPointRepository.delete(delPoint);
            mapLineRepository.delete(mapLine);
            if(transportOrder.getId() != null){
                transportOrderRepository.deleteById(transportOrder.getId());
            }


            throw new ApplicationException(ApplicationExceptionEnum.TRANSPORT_ORDER_SUBMIT_ERROR);
        }

        return transportOrder;
    }

    private void validateAndInit(TranspOrderSubmitDto submitDto){

        String token = HttpUtil.getRequest().getHeader("Authorization");
        Long idUser = null;
        log.info("token>>{}",token);

        if(StrUtil.isBlank(token)){
            throw new ApplicationException(ApplicationExceptionEnum.TRANSPORT_ORDER_SUBMIT_ERROR.getCode(),"请先执行登录操作");

        }else{
            idUser = JwtUtil.getUserId(token);
            if(idUser == null){
                throw new ApplicationException(ApplicationExceptionEnum.TRANSPORT_ORDER_SUBMIT_ERROR.getCode(),"token异常");
            }

        }


        submitDto.setUserId(idUser);



        List<MapPointDto> pointDtoList = submitDto.getMapPoints();

        if(CollectionUtils.isEmpty(pointDtoList) || pointDtoList.size() < 2){
            throw new ApplicationException(ApplicationExceptionEnum.TRANSPORT_ORDER_SUBMIT_ERROR.getCode(),"请选择起点和终点");
        }

        if(submitDto.getLoadingType() == null){
            throw new ApplicationException(ApplicationExceptionEnum.TRANSPORT_ORDER_SUBMIT_ERROR.getCode(),"请选择承载类型");
        }

        if(StrUtil.isBlank(submitDto.getMobile())){
            throw new ApplicationException(ApplicationExceptionEnum.TRANSPORT_ORDER_SUBMIT_ERROR.getCode(),"请输入手机号");
        }

        submitDto.setSubmitTime(new Date());

    }


}
